<?php
//declare (strict_types = 1);

namespace app\common\business;

use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\User as UserModel;
use think\Exception;

class User
{
   public $userObj = null;
   public function __construct()
   {
       $this->userObj = new UserModel();
   }


    public function login($data)
    {

        $redisCode = cache(config('redis.code_pre') . $data['phone_number']);

        if (empty($redisCode) || $redisCode != $data['code']) {
            throw new \think\Exception('验证码不存在', -1009);
        }

        //需要去判断表 是否有用户记录
        $usermodel = new UserModel();
        $user = $usermodel->getUserByPhoneNumber($data['phone_number']);

        //如果没有该手机号码,说该用户不存在,需要新增用户

        if (!$user) {
            $username = 'fendou-' . $data['phone_number'];
            $userData = [
                'username' => $username,
                'phone_number' => $data['phone_number'],
                'type' => $data['type'],
                'status' => config('status.mysql.table_normal'),
            ];

            try {
                $usermodel->save($userData);
                $userId = $usermodel->id;
            } catch (\Exception $e) {
                throw new Exception('数据库内部异常');
            }
        } else {
            //更新表
            $userId = $user->id;
            $username = $user->username;

        }

        //生成token
        $token = Str::getLoginToken($data['phone_number']);
        $redisData = [
            'id' => $userId,
            'username' => $username
        ];
        $res = cache(config('redis.token_pre') . $token, $redisData, Time::userLoginExpiresTime($data['type']));

        return $res ? ['token' => $token, 'username' => $username] : false;
    }

    /**返回正常用户数据
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserById($id){
        $usermodel = new UserModel();
        $user = $usermodel->getUserById($id);
        if(!$user||$user->status!=config('status.mysql.table_normal')){
            return [];
        }
        return $user->toArray();
    }
    public function getNormalUserByUsername($data){
        $usermodel = new UserModel();
        $user = $usermodel->where('username',$data)->find();
        
        return $user;
    }

    public function update($id,$data){
        //检查用户名是否存在
        $user= $this->getNormalUserByUsername($data['username']);
        if($user && $user['id']!=$id){
            throw new \think\Exception('该用户已经存在请重新设置');
        }

        // //更新用户
        return $this->userObj->updateById($id,$data);
    }
}
